package com.example.demo.service.impl;

import com.example.demo.entity.Book;
import com.example.demo.repository.BookRepository;
import com.example.demo.service.BookService;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@Service
public class BookServiceImpl implements BookService {

    @Resource
    private BookRepository repository;

    @Override
    public Optional<Book> add(Book req) throws Exception {
        return Optional.of(repository.save(req));
    }

    @Override
    public Optional<Book> update(Book req) throws Exception {
        return Optional.of(repository.save(req));
    }

    @Override
    public Optional<Boolean> deleteById(String optUserId, Long id) throws Exception {
        Optional<Book>  optional = queryById(id);
        optional.ifPresent(item -> repository.delete(item));
        return Optional.empty();
    }

    @Override
    public Optional<Book> queryById(Long id) throws Exception {
        return repository.findById(id);
    }

    @Override
    public Optional<List<Book>> list(Book req) throws Exception {
        return Optional.empty();
    }

    @Override
    public Optional<Page<Book>> page(Book req) throws Exception {
        return Optional.empty();
    }

    @Override
    public boolean isExist(Long orgCode, String barCode) throws Exception {
        final Book req = new Book();
        req.setOrgCode(orgCode);
        req.setBarCode(barCode);
        final ExampleMatcher matcher = ExampleMatcher.matchingAll()
                .withMatcher("orgCode", ExampleMatcher.GenericPropertyMatchers.caseSensitive().exact())
                .withMatcher("barCode", ExampleMatcher.GenericPropertyMatchers.caseSensitive().exact());
        Optional<Book> optional = repository.findOne(Example.of(req, matcher));
        if (optional.isPresent()) {
            return true;
        }
        return false;
    }
}
